#include <sxMSS_PreviewRecorder.h>

Sx::Simulation::Recording::MSS_PreviewRecorder::MSS_PreviewRecorder(const std::shared_ptr<MassSpringSimulation>& simulation, const std::shared_ptr<MSS_PreviewRecording>& recording) :
	AbstractRecorder(recording) {
	this->simulation = simulation;
}

Sx::Simulation::Recording::MSS_PreviewRecorder::~MSS_PreviewRecorder() {}

/* When to record a frame */
bool Sx::Simulation::Recording::MSS_PreviewRecorder::recordSteps(unsigned int n, unsigned int m) {
	if ( this->recordingFrames == false ) return false;
	if ( n == 0 || m == 0 ) return false;
	if ( simulation == nullptr ) return false;

	for ( unsigned int i = 0; i < n; i++ ) {
		// Record every m_th frame (allow the abstract recorder to take care of
		// it; it will call the processFrame(MSS_PreviewKeyFrame) function).
		if ( i % m == 0 ) {
			AbstractRecorder::processFrame();
		}

		// Update the simulation
		simulation->update();
	}

	return false;
}

/* How to record a frame */
bool Sx::Simulation::Recording::MSS_PreviewRecorder::processFrame(MSS_PreviewKeyFrame& frame) {
	if ( this->simulation == nullptr ) {
		std::cerr << "[MSS_PreviewRecorder:processFrame] Error: Cannot process frame for nullptr simulation." << std::endl;
		std::cerr << "  Internal recording unmodified." << std::endl;
		return false;
	}

	for ( unsigned int i = 0; i < this->simulation->getMeshCount(); i++ ) {
		MSM_PreviewState& meshPreviewStates = frame.meshPreviewStates.getNext();
		if ( this->simulation->getMesh(i)->isStatic() == false )
			meshPreviewStates.save(this->simulation->getMesh(i));
	}

	return false;
}
